import { release } from "node:os";
import { fileURLToPath } from "node:url";
import { join, dirname } from "node:path";
import {
  type MenuItem,
  type MenuItemConstructorOptions,
  app,
  Menu,
  shell,
  ipcMain,
  BrowserWindow,
  dialog
} from "electron";

// The built directory structure
//
// ├─┬ dist-electron
// │ ├─┬ main
// │ │ └── index.js    > Electron-Main
// │ └─┬ preload
// │   └── index.mjs    > Preload-Scripts
// ├─┬ dist
// │ └── index.html    > Electron-Renderer
//
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
process.env.DIST_ELECTRON = join(__dirname, "..");
process.env.DIST = join(process.env.DIST_ELECTRON, "../dist");
process.env.PUBLIC = process.env.VITE_DEV_SERVER_URL
  ? join(process.env.DIST_ELECTRON, "../public")
  : process.env.DIST;
// 是否为开发环境
const isDev = import.meta.env.MODE !== "production";

// Disable GPU Acceleration for Windows 7
if (release().startsWith("6.1")) app.disableHardwareAcceleration();

// Set application name for Windows 10+ notifications
if (process.platform === "win32") app.setAppUserModelId(app.getName());

if (!app.requestSingleInstanceLock()) {
  app.quit();
  process.exit(0);
}

// Remove electron security warnings
// This warning only shows in development mode
// Read more on https://www.electronjs.org/docs/latest/tutorial/security
// process.env['ELECTRON_DISABLE_SECURITY_WARNINGS'] = 'true'

let win: BrowserWindow | null = null;
// Here, you can also use other preload
const preload = join(__dirname, "../preload/index.mjs");
const url = process.env.VITE_DEV_SERVER_URL;
const indexHtml = join(process.env.DIST, "index.html");

// 创建菜单
function createMenu() {
  const menu = Menu.buildFromTemplate(
    appMenu() as (MenuItemConstructorOptions | MenuItem)[]
  );
  Menu.setApplicationMenu(menu);
}

async function createWindow() {
  // 设置 About Panel 的选项
  app.setAboutPanelOptions({
    applicationName: "Vue3 Admin 前端脚手架 (Electron版)",
    applicationVersion: "",
    credits: `版本: ${app.getVersion()}
Electron: ${process.versions.electron}
Chromium: ${process.versions.chrome}
Node.js: ${process.versions.node}
V8: ${process.versions.v8}
OS: ${process.platform} ${process.arch} ${release()}
  `
    // 在 macOS 上，你可以添加一个自定义字符串来显示 Chrome 版本
    // 注意：这只是一个字符串，你需要自己获取并格式化
    // process.versions.chrome 可以获取 Chromium 版本
    // process.versions.node 可以获取 Node.js 版本
    // process.versions.v8 可以获取 V8 引擎版本
    // 其他你希望显示的信息
    // 例如，你可以将更多信息放在 credits 或 copyright 中，或者构建一个更长的字符串
    // 这里我们尝试将 Chrome 版本包含在 applicationName 中，但更常见是放在 credits 或单独的 customInfo 字段（如果 Electron 支持）
    // 实际上，Electron 官方的 setAboutPanelOptions 并没有一个直接的字段来显示 "Chrome 版本"
  });
  win = new BrowserWindow({
    width: 1280,
    height: 800,
    minWidth: 1024,
    minHeight: 768,
    show: false,
    icon: join(process.env.PUBLIC, "favicon.ico"),
    webPreferences: {
      preload
      // Warning: Enable nodeIntegration and disable contextIsolation is not secure in production
      // nodeIntegration: true,

      // Consider using contextBridge.exposeInMainWorld
      // Read more on https://www.electronjs.org/docs/latest/tutorial/context-isolation
      // contextIsolation: false,
    }
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    // electron-vite-vue#298
    win.loadURL(url);
    // Open devTool if the app is not packaged
    // win.webContents.openDevTools();
  } else {
    win.loadFile(indexHtml);
  }

  win.once("ready-to-show", () => {
    win.maximize(); // 最大化窗口
    win.show(); // 然后再显示窗口
  });

  if (isDev) win.webContents.openDevTools();

  createMenu();

  // Test actively push message to the Electron-Renderer
  win.webContents.on("did-finish-load", () => {
    win?.webContents.send("main-process-message", new Date().toLocaleString());
  });

  // Make all links open with the browser, not with the application
  win.webContents.setWindowOpenHandler(({ url }) => {
    if (url.startsWith("https:")) shell.openExternal(url);
    return { action: "deny" };
  });
  // win.webContents.on('will-navigate', (event, url) => { }) #344

  // 监听窗口关闭事件
  win.on("close", event => {
    // 阻止默认关闭行为
    event.preventDefault();

    // 弹出确认对话框
    dialog
      .showMessageBox(win, {
        type: "question",
        buttons: ["是", "否"],
        title: "确认关闭",
        message: "您确定要关闭应用程序吗？"
      })
      .then(result => {
        if (result.response === 0) {
          // 用户点击了 '是'

          // 向渲染进程发送消息，通知它执行关闭前的清理工作
          // 我们会等待渲染进程的响应
          win.webContents.send("app-closing");

          // 可以在这里设置一个超时，以防渲染进程没有响应
          setTimeout(() => {
            if (!win.isDestroyed()) {
              win.destroy();
            }
          }, 2000); // 2秒后强制关闭，防止卡死
        }
      })
      .catch(() => {});
  });

  // 监听 focus 事件
  win.on("focus", () => {
    win.webContents.send("window-focus");
  });

  // 监听 blur 事件
  win.on("blur", () => {
    win.webContents.send("window-blur");
  });
}

app.whenReady().then(createWindow);

// 监听渲染进程发送回来的 'app-ready-to-close' 消息
ipcMain.on("app-ready-to-close", () => {
  if (win && !win.isDestroyed()) {
    win.destroy(); // 渲染进程完成清理，现在可以安全关闭窗口
  }
});

// 当所有窗口都被关闭时退出应用
app.on("window-all-closed", () => {
  win = null;
  if (process.platform !== "darwin") app.quit();
});

app.on("second-instance", () => {
  if (win) {
    // Focus on the main window if the user tried to open another
    if (win.isMinimized()) win.restore();
    win.focus();
  }
});

// 当应用程序被激活时创建窗口 (macOS)
app.on("activate", () => {
  const allWindows = BrowserWindow.getAllWindows();
  if (allWindows.length) {
    allWindows[0].focus();
  } else {
    createWindow();
  }
});

// 菜单栏 https://www.electronjs.org/zh/docs/latest/api/menu-item#%E8%8F%9C%E5%8D%95%E9%A1%B9
const appMenu = () => {
  if (!isDev) return [];
  return [
    {
      label: "DEBUG: ON",
      submenu: [
        { label: "关于", role: "about" },
        { label: "开发者工具", role: "toggleDevTools" },
        { label: "强制刷新", role: "forcereload" },
        { label: "退出", role: "quit" }
      ]
    }
  ];
};

// New window example arg: new windows url
ipcMain.handle("open-win", (_, arg) => {
  const childWindow = new BrowserWindow({
    webPreferences: {
      preload,
      nodeIntegration: true,
      contextIsolation: false
    }
  });

  if (process.env.VITE_DEV_SERVER_URL) {
    childWindow.loadURL(`${url}#${arg}`);
  } else {
    childWindow.loadFile(indexHtml, { hash: arg });
  }
});

// 打开关于弹窗
ipcMain.on("open-about-panel", () => {
  app.showAboutPanel();
});

// 任务栏窗口闪烁
ipcMain.on("flash-taskbar", () => {
  if (win) {
    // true 表示开始闪烁，false 表示停止闪烁
    win.flashFrame(true);

    // 可选：几秒后停止闪烁
    // setTimeout(() => {
    //   win.flashFrame(false);
    // }, 5000); // 5 秒后停止闪烁
  }
});

// 监听来自渲染进程的 'quit-app' 事件
ipcMain.on("quit-app", () => {
  app.quit(); // 接收到退出请求后，关闭应用
});
